﻿using Microsoft.AspNetCore.Mvc;
using NuGet.Common;
using PesticideManage.API.Models;
using PesticideManage.API.Services.Files.Models;
using PesticideManage.Domain.AggregatesModel.BatchQRCodeAggregate;
using Shang.COSXML;
using System.Net;
using System.Resources;
using System.Text;
using System.Web;

namespace PesticideManage.API.Services.Files;

public class TencentCosService : IStoreService
{
    private readonly CosXmlService _cosXmlService;
    private Uri BaseAddress { get; }
    public string CurrentName { get; } = nameof(TencentCosService);
    public StoreSource StoreSource { get; } = StoreSource.TencentCos;

    public TencentCosService(CosXmlService cosXmlService)
    {
        _cosXmlService = cosXmlService;
        BaseAddress = cosXmlService.BaseAddress ?? throw new ArgumentNullException(nameof(cosXmlService.BaseAddress));
    }
    public Task CreateFileAsync(IFormFile formFile)
    {
        return _cosXmlService.PutFileAsync(formFile);
    }
    public IActionResult GetFile(string fileName, string username)
    {
        string url = $"{BaseAddress}{Config.FilePath}/{username}/{WebUtility.UrlEncode(fileName)}";
        //url = WebUtility.UrlEncode(url);
        return new RedirectResult(url);
    }
    public async Task CreateFileAsync(string fileName, string username, StringBuilder sb)
    {
        char[] dest = new char[sb.Length];
        sb.CopyTo(0, dest, 0, sb.Length);
        byte[] bytes = Encoding.UTF8.GetBytes(dest);
        await _cosXmlService.PutFileAsync($"{Config.FilePath}/{username}/{fileName}", bytes);
    }

    public void DeleteFile(string fileName, string username)
    {
        _ = _cosXmlService.DeleteObjectAsync($"{Config.FilePath}/{username}/{fileName}");
    }
}